package model

import (
	"ginblog/utils/errmsg"
	"gorm.io/gorm"
)

type Article struct {
	Category Category `gorm:"foreignkey:Cid"`
	gorm.Model
	Title   string `gorm:"type:varchar(100);not null" json:"title"`
	Cid     int    `gorm:"type:int;not null" json:"cid"`
	Desc    string `gorm:"type:varchar(200)" json:"desc"`
	Content string `gorm:"type:longtext" json:"content"`
	Img     string `gorm:"type:varchar(100)" json:"img"`
}

// 新增文章
func CreateArticle(article *Article) int {
	err := db.Create(&article).Error
	if err != nil {
		return errmsg.ERROR // 500
	}
	return errmsg.SUCCESS // 200
}

// 查询所有文章列表
func GetAllArticles(pageSize, pageNum int) ([]Article, int) {
	var allArticles []Article
	err := db.Preload("Category").Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&allArticles).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errmsg.ERROR
	}
	return allArticles, errmsg.SUCCESS
}

// 查询单个分类下的所有文章
func GetCategoryArticles(id, pageSize, pageNum int) ([]Article, int) {
	var categoryArticles []Article
	err := db.Preload("Category").Limit(pageSize).Offset((pageNum-1)*pageSize).Where("cid = ?", id).Find(&categoryArticles).Error
	if err != nil {
		return nil, errmsg.ErrorCategoryNotExist
	}
	return categoryArticles, errmsg.SUCCESS
}

// 查询单个文章信息
func GetArticleInfo(id int) (Article, int) {
	var article Article
	err := db.Preload("Category").Where("id = ?", id).First(&article).Error
	if err != nil {
		return Article{}, errmsg.ErrorArticleNotExist
	}
	return article, errmsg.SUCCESS
}

// 编辑文章
func EditArticle(id int, newArticle *Article) int {
	var article Article
	var maps = make(map[string]interface{})
	maps["title"] = newArticle.Title
	maps["content"] = newArticle.Content
	maps["cid"] = newArticle.Cid
	maps["desc"] = newArticle.Desc
	maps["img"] = newArticle.Img
	err := db.Model(&article).Where("id = ?", id).Updates(maps).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

// 删除文章
func DeleteArticle(id int) int {
	var article Article
	err := db.Where("id = ?", id).Delete(&article).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}
